package site.hanzhe.did.entity;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Docker清单实体类
 *
 * @author 张涵哲
 * @since 2024-06-14 19:19:26
 */
@Setter
public class DockerManifest {

    private JSONObject jsonObject;

    /**
     * 将JSON字符串解析为DockerManifest对象
     *
     * @author 张涵哲
     * @since 2024-06-14 19:31:26
     */
    public static DockerManifest parse(String responseBody) {
        // SchemaVersion版本判断
        JSONObject jsonObject = JSONUtil.parseObj(responseBody);
        Integer schemaVersion = jsonObject.get("schemaVersion", Integer.class);
        if (schemaVersion == 1) {
            Console.log("此镜像为旧版的schemaVersion1镜像，作者正在进行适配，请耐心等待");
            System.exit(0);
        }

        DockerManifest dockerManifest = new DockerManifest();
        dockerManifest.setJsonObject(jsonObject);
        return dockerManifest;
    }

    /**
     * 获取平台架构列表（过滤了无法识别的平台架构，按照英文字母顺序排序）
     *
     * @author 张涵哲
     * @since 2024-06-14 20:30:19
     */
    public List<Platform> getPlatforms() {
        List<Platform> platforms = new ArrayList<>();
        for (Object manifest : jsonObject.getJSONArray("manifests")) {
            JSON manifestJson = JSONUtil.parse(manifest);
            Platform platform = new Platform();
            platform.setOs(manifestJson.getByPath("platform.os", String.class));
            platform.setArch(manifestJson.getByPath("platform.architecture", String.class));
            platform.setVariant(manifestJson.getByPath("platform.variant", String.class));
            platform.setDigest(manifestJson.getByPath("digest", String.class));
            platforms.add(platform);
        }
        return platforms.stream()
                .filter(platform -> StrUtil.isAllNotBlank(platform.getOs(), platform.getArch()))
                .filter(platform -> !StrUtil.equalsAny("unknown", platform.getOs(), platform.getArch()))
                .sorted(Comparator.comparing(Platform::toString))
                .collect(Collectors.toList());
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this.jsonObject);
    }

}
